﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;

namespace MCB.Trading.Generic
{
    public class OrderBook<TOrderKey, TOrder, TProduct> : IEnumerable<TOrder>
        where TOrder : IOrder<TOrderKey, TProduct>
    {
        protected ConcurrentDictionary<TOrderKey, TOrder> _orders = new ConcurrentDictionary<TOrderKey, TOrder>();

        protected TOrder _buyTopOfBook;
        protected TOrder _sellTopOfBook;

        public TOrder BuyTopOfBook 
        {
            get { return _buyTopOfBook; }
            set 
            {
                if (_buyTopOfBook != null)
                {
                    _buyTopOfBook.TopOfBook = false;
                    _buyTopOfBook = value;
                    _buyTopOfBook.TopOfBook = true;
                }
                else
                {
                    _buyTopOfBook = value;
                    _buyTopOfBook.TopOfBook = true;
                }
            } 
        }

        public TOrder SellTopOfBook
        {
            get { return _sellTopOfBook; }
            set
            {
                if (_sellTopOfBook != null)
                {
                    _sellTopOfBook.TopOfBook = false;
                    _sellTopOfBook = value;
                    _sellTopOfBook.TopOfBook = true;
                }
                else
                {
                    _sellTopOfBook = value;
                    _sellTopOfBook.TopOfBook = true;
                }
            }
        }

        public OrderBook()
        {
        }

        public void Add(TOrder item)
        {
            _orders.TryAdd(item.Id, item);
        }

        public void Remove(TOrderKey key)
        {
            TOrder item;
            _orders.TryRemove(key, out item);
        }

        public IEnumerator<TOrder> GetEnumerator()
        {
            return _orders.Values.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
